package com.jiayen.util;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.jiayen.R;

/**
 * Created by jiayen on 16/10/14.
 */

public class ToasUtil {

    private static final int TOAST_DELAY = 1000;

    public static Toast topToast;
    public static   TextView msgText ;

    private static Toast toast;
    private static Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == TOAST_DELAY && toast != null)
                toast.cancel();
        }
    };

    /**
     * 共用弹出提示方便后续修改toast框
     * @param context
     * @param msg
     */
    public static void toast(Context context,String msg){
//        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();

        if(toast != null)
            toast.cancel();
        handler.removeMessages(TOAST_DELAY);
        toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
        toast.show();
        handler.sendEmptyMessageDelayed(TOAST_DELAY, TOAST_DELAY);
    }
    public static void toast(Context context, int msgId){
        toast(context, context.getResources().getString(msgId));
    }

    /**
     * 共用弹出提示方便后续修改toast框
     * @param context
     * @param msg
     */
    public static void toastTop(Context context,String msg){
        topToast= new Toast(context);
//        if(topToast==null){
            View view = LayoutInflater.from(context).inflate(R.layout.top_toast,null);
            msgText = (TextView) view.findViewById(R.id.name);
            topToast.setGravity(Gravity.TOP,0,0);
            topToast.setDuration(Toast.LENGTH_SHORT);

//        }

//        if(msgText!=null)
            msgText.setText(msg);

        topToast.setView(view);
        topToast.show();
    }
}
